package gen.tools.role;

import gen.tools.Widgets;
import gen.tools.structures.RoleAssign;
import gen.tools.structures.S2;

import java.io.IOException;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.util.ArrayList;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.google.gson.Gson;

public class QueryEmpsWithRole extends HttpServlet {
	private static final long serialVersionUID = 1L;
       
    public QueryEmpsWithRole() {
        super();
    }

	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		doPost(request,response);
	}

	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		
		final Widgets wid = new Widgets();
		request.setCharacterEncoding( wid.UIcodeSet );
		response.setContentType("application/json");
		response.setCharacterEncoding( wid.UIcodeSet );
		
		final String subsysId = request.getParameter("subsysId");
		final int roleId = Integer.parseInt( request.getParameter("roleId") );
		
		final ArrayList<S2> in = new ArrayList<S2>();		//擁有 指定子系統下，擁有指定角色的人員
		final ArrayList<S2> out = new ArrayList<S2>();		//非上述的其它人
		final RoleAssign ra = new RoleAssign();
		
		String sql = "";
		
		Connection conn = null;
		PreparedStatement ps = null;
		ResultSet rs = null;
		
		try {
			conn = wid.getConn();
			
			//所有子系統下擁有指定角色的人
			sql = "SELECT t1.empId,t2.empName FROM mpemprolesubsys t1,emps t2 WHERE t1.empId=t2.empId AND t1.subsysId=? AND t1.roleId=?";
			ps = conn.prepareStatement( sql );
			ps.setString(1, subsysId);
			ps.setInt(2, roleId);
			rs = ps.executeQuery();
			while ( rs.next() ) {
				final S2 s2 = new S2();
				s2.setS1( rs.getString("empId") );
				s2.setS2( rs.getString("empName") );
				in.add(s2);
			}
			
			//未擁有此角色的人
			sql = "SELECT empId,empName FROM emps WHERE empId NOT IN (SELECT empId FROM mpemprolesubsys WHERE subsysId=? AND roleId=?)";
			ps = conn.prepareStatement( sql );
			ps.setString(1, subsysId);
			ps.setInt(2, roleId);
			rs = ps.executeQuery();
			while ( rs.next() ) {
				final S2 s2 = new S2();
				s2.setS1( rs.getString("empId") );
				s2.setS2( rs.getString("empName") );
				out.add(s2);
			}
		} catch (Exception e) {
			wid.errLog(e);
		} finally {
			try {
				if ( rs !=null ) {rs.close();}
				if ( ps !=null ) {ps.close();}
				if ( conn !=null ) {conn.close();}	
			} catch (Exception e) { e.printStackTrace(); };
			
		}
		
		ra.setInList(in);
		ra.setOutList(out);
		
		response.getWriter().write( new Gson().toJson( ra ) );
	}

}
